#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import sys
from pathlib import Path

def remove_copyright_comment(file_path):
    """
    删除文件头部的版权注释
    """
    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()

        original_content = content
        
        # 检查是否是C/C++文件开头的版权注释
        # 只处理文件开头的注释块，且包含版权相关信息
        lines = content.split('\n')
        
        # 找到第一个非空白行
        start_idx = 0
        while start_idx < len(lines) and lines[start_idx].strip() == '':
            start_idx += 1
        
        # 版权相关关键词
        copyright_keywords = [
            'Copyright', 'copyright', 'Copyright (c)', '版权',
            'All Rights Reserved', 'FilePath', 'Author', 'Date',
            'LastEditors', 'LastEditTime', 'Version'
        ]
        
        # 检查是否以多行注释开始
        if start_idx < len(lines) and (lines[start_idx].strip().startswith('/**') or lines[start_idx].strip().startswith('/*')):
            # 找到注释结束位置
            end_idx = start_idx + 1
            while end_idx < len(lines):
                if '*/' in lines[end_idx]:
                    end_idx += 1
                    break
                end_idx += 1
            
            # 检查注释内容是否包含版权相关关键词
            comment_block = '\n'.join(lines[start_idx:end_idx])
            
            # 如果包含版权相关关键词，则删除该注释块
            if any(keyword in comment_block for keyword in copyright_keywords):
                # 保留开头的空行
                new_lines = lines[:start_idx] + lines[end_idx:]
                # 去除注释后可能产生的多余空行
                while len(new_lines) > 0 and new_lines[0].strip() == '':
                    new_lines.pop(0)
                
                new_content = '\n'.join(new_lines)
                
                # 如果文件内容发生变化，则写回文件
                if new_content != original_content:
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write(new_content)
                    print(f"已处理: {file_path}")
                    return True
        
        # 检查是否以连续的单行注释开始（用于处理 // 形式的版权注释）
        elif start_idx < len(lines) and lines[start_idx].strip().startswith('//'):
            end_idx = start_idx
            # 找到连续单行注释的结束位置
            while end_idx < len(lines) and lines[end_idx].strip().startswith('//'):
                end_idx += 1
            
            # 检查注释内容是否包含版权相关关键词
            comment_block = '\n'.join(lines[start_idx:end_idx])
            
            # 如果包含版权相关关键词，则删除该注释块
            if any(keyword in comment_block for keyword in copyright_keywords):
                # 保留开头的空行
                new_lines = lines[:start_idx] + lines[end_idx:]
                # 去除注释后可能产生的多余空行
                while len(new_lines) > 0 and new_lines[0].strip() == '':
                    new_lines.pop(0)
                
                new_content = '\n'.join(new_lines)
                
                # 如果文件内容发生变化，则写回文件
                if new_content != original_content:
                    with open(file_path, 'w', encoding='utf-8') as f:
                        f.write(new_content)
                    print(f"已处理: {file_path}")
                    return True
        
        return False

    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {str(e)}")
        return False

def process_directory(directory):
    """
    处理指定目录下的所有.h和.cpp文件
    """
    # 获取目录的绝对路径
    dir_path = Path(directory).resolve()
    
    if not dir_path.exists():
        print(f"目录不存在: {dir_path}")
        return 0, 0

    # 统计信息
    total_files = 0
    modified_files = 0

    # 遍历目录
    for root, _, files in os.walk(dir_path):
        for file in files:
            if file.endswith(('.h', '.cpp')):
                total_files += 1
                file_path = Path(root) / file
                if remove_copyright_comment(file_path):
                    modified_files += 1

    return total_files, modified_files

def main():
    """
    主函数
    """
    # 要处理的目录列表
    directories = ['src', 'tests']
    
    print("开始处理文件...")
    print("-" * 50)

    total_processed = 0
    total_modified = 0

    for directory in directories:
        print(f"\n处理目录: {directory}")
        processed, modified = process_directory(directory)
        total_processed += processed
        total_modified += modified

    print("\n处理完成!")
    print("-" * 50)
    print(f"总文件数: {total_processed}")
    print(f"修改文件数: {total_modified}")
    print(f"未修改文件数: {total_processed - total_modified}")

if __name__ == "__main__":
    main() 